package be.kuleuven.mume.query;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import javax.jdo.PersistenceManager;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public abstract class UpdateQueryHelper<T> extends QueryHelper<Boolean>{
	private String stringKey;
	
	public UpdateQueryHelper(String stringKey) {
		this.stringKey = stringKey;
	}
	
	@Override
	protected Boolean execute(PersistenceManager pm) {
		
		Key key = KeyFactory.stringToKey(stringKey);
		Class<T> c = getGenericType();
		T obj = (T)pm.getObjectById(c, key);
	
		if(doUpdate(obj)) {
			pm.makePersistent(obj);
			return true;
		}
		return false;
	}
	
	@Override
	public Boolean executeAtomicQuery() {
		Boolean result = super.executeAtomicQuery();
		if(result == null)
			result = false;
		return result;
	}
	
	/**
	 * Needs to be overriten if you would like to extend it.
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected Class<T> getGenericType() {
		Class<?> c = this.getClass();
		ParameterizedType d = (ParameterizedType)c.getGenericSuperclass();
		Type f = d.getActualTypeArguments()[0];
		return (Class<T>)f;
	}

	public abstract Boolean doUpdate(T objectToUpdate);

}
